<?php


namespace App\Services;
use GuzzleHttp\Cookie\CookieJar;
use QL\QueryList;
use QL\Ext\CurlMulti;
use Illuminate\Support\Facades\Log;

/**
 * Erp集成查询服务
 * Class ErpService
 * @package App\Services
 */
class ErpService
{

    private $ql;
    public function __construct()
    {
        $this->ql = QueryList::getInstance();
        $this->ql->use(CurlMulti::class);
    }

    /**
     * 获取查询结果
     * @param $barcode
     */
    public function query($barcode){

        $data = array();
        $qslist = $this->queryStore($barcode);
//        $pklist = $this->packing($barcode);
//        $aplist = $this->applyList($barcode);
        return $qslist;
    }

    /**
     * 仓库查询
     * @param $barcode
     * @return mixed
     */
    public function queryStore($barcode){
        $data = array();
        $hashkey = md5('queryStore'.'-'.$barcode);
        if(\Redis::exists($hashkey)){
            $jsonstr = \Redis::get($hashkey);
            $data = isset($jsonstr) ? json_decode($jsonstr, true) : array();
        }else {
            $barcode_arr = explode(' ', $barcode);
            if (!empty($barcode_arr)) {
                $this->ql->post('http://jyj.eccang.com/default/index/login', [
                    'userName' => 'PHP03',
                    'userPass' => 'PHP123456'
                ])->get('http://jyj.eccang.com/warehouse/Inventory/new-list/page/1/pageSize/20');
                foreach ($barcode_arr as $item) {
                    //                Form表单
                    //                http://jyj.eccang.com/warehouse/Inventory/new-list/page/1/pageSize/20
                    //                sale_status:
                    //                product_receive_status:
                    //                product_status: 1
                    //                category[]:
                    //                operationType: E1_like
                    //                product_barcode: J040626-WG-WHITE_TABLE
                    //                product_title_type: like_product_title
                    //                like_product_title:
                    //                supplier_id:
                    //                supplier_name:
                    //                order_by:
                    //                is_recommend_lc_code:
                    //                lcType: 1
                    //                recommend_lc_code_like:
                    //                prl_id:
                    //                person_type: 1
                    //                person:
                    //                date_type: 1
                    //                dateFor:
                    //                dateTo
                    //获取目的地列表
                    $post_data = [
                        'sale_status' => '',
                        'product_receive_status' => '',
                        'product_status' => 1,
                        'category' => [],
                        'operationType' => 'E1', //E1、E1_like
                        'product_barcode' => $item,
                        'product_title_type' => 'like_product_title',
                        'supplier_id' => '',
                        'supplier_name' => '',
                        'order_by' => '',
                        'is_recommend_lc_code' => '',
                        'lcType' => 1,
                        'recommend_lc_code_like' => '',
                        'prl_id' => '',
                        'person_type' => 1,
                        'person' => '',
                        'date_type' => 1,
                        'dateFor' => '',
                        'dateTo' => '',

                    ];
                    $this->ql->post('http://jyj.eccang.com/warehouse/Inventory/new-list/page/1/pageSize/1000', $post_data);
                    $content = $this->ql->getHtml();
                    $result = json_decode($content, true);
//                    dd($content);
                    if(!empty($result['data'])) {
                       foreach ($result['data'] as $item) {
                           $nitem = array();
                           if(!empty($item['warehouseDetail'])){
                               array_pop($item['warehouseDetail']);
                                foreach ($item['warehouseDetail'] as $oitem){
                                    if($oitem['pi_purchase_onway'] > $oitem['pi_no_stock']) {
                                        $nitem['product_barcode'] = $item['product_barcode']; //产品代码
                                        $nitem['product_title'] = $item['product_title']; //产品名称
                                        $nitem['warehouse'] = $oitem['warehouse']; //仓库
                                        $nitem['pi_purchase_onway'] = strval($oitem['pi_purchase_onway']); //采购在途
                                        $nitem['pi_in_used'] = strval($oitem['pi_in_used']); //可用、可售
                                        $nitem['pi_warning_qty'] = strval($oitem['pi_warning_qty']); //预警
                                        $nitem['pi_can_sale_days'] = strval($oitem['pi_can_sale_days']); //可售天数
                                        $nitem['pi_no_stock'] = strval($oitem['pi_no_stock']); //缺货
                                        $nitem['pi_no_stock_days'] = strval($oitem['pi_no_stock_days']); //缺货天数
                                        $nitem['expected_date'] = 0; //预计到货日期
                                        //获取采购在途数据
                                        $pdata = [
                                            'wid' => $oitem['warehouse_id'],
                                            'pid' => $oitem['product_id'],
                                            'status' => 5
                                        ];
                                        $this->ql->post('http://jyj.eccang.com/warehouse/inventory/get-purchase-on-way-detail/', $pdata);
                                        $ltcontent = $this->ql->getHtml();
                                        $ltrs = json_decode($ltcontent, true);
//                                        dd($ltrs);
                                        if(!empty($ltrs)){
                                            $num = 0;
                                            foreach ($ltrs as $ors){
                                                $num += $ors['rd_receiving_qty'];
                                                if($num >= $oitem['pi_no_stock']){
                                                    $nitem['expected_date'] = $ors['expected_date'];
                                                    break;
                                                }
                                            }
                                        }
                                        array_push($data, $nitem);
                                    }
                                }
                           }
                       }
                    }
                }
            }

            \Redis::setex($hashkey, 60, json_encode($data));
        }

        return $data;
    }

    /**
     * 获取拣货列表
     * @param $barcode
     */
    public function packing($barcode){

        $data = array();
        $hashkey = md5('packing'.'-'.$barcode);
        if(\Redis::exists($hashkey)){
            $jsonstr = \Redis::get($hashkey);
            $data = isset($jsonstr) ? json_decode($jsonstr, true) : array();
        }else {
            $barcode_arr = explode(' ', $barcode);
            if (!empty($barcode_arr)) {
                $this->ql->post('http://jyj.eccang.com/default/index/login',[
                    'userName' => 'PHP03',
                    'userPass' => 'PHP123456'
                ])->get('http://jyj.eccang.com/transfer/packing/list?quick=141');
                foreach ($barcode_arr as $item) {
//                    form表单
//                    http://jyj.eccang.com/transfer/packing/list/page/1/pageSize/20
//                    E7:
//                    is_product_combine:
//                    E2:
//                    E12:
//                    operationType: E1
//                    operationCode:
//                    product_barcode: PALLET
//                    remark:
//                    destination:
//                    timeType: E1
//                    dateFor:
//                    dateTo:
                    $post_data = [
                        'E7' => '',
                        'is_product_combine' => '',
                        'E2' => '',
                        'E12' => '',
                        'operationType' => 'E1', //E1、E1_like
                        'operationCode' => '',
                        'product_barcode' => $item,
                        'remark' => '',
                        'destination' => '',
                        'timeType' => 'E1',
                        'dateFor' => '',
                        'dateTo' => ''
                    ];

                    $this->ql->post('http://jyj.eccang.com/transfer/packing/list/page/1/pageSize/1000', $post_data);
                    $content =  $this->ql->getHtml();
                    $result = json_decode($content, true);
//                    dd($result);
                    if(!empty($result['data'])) {
                        $data = array_shift($result['data']);
                    }
                }
            }

            \Redis::setex($hashkey, 60, json_encode($data));
        }
        return $data;
    }

    /**
     * 获取申购单列表
     * @param $barcode
     */
    public function applyList($barcode){

        $data = array();
        $hashkey = md5('applyList'.'-'.$barcode);
        if(\Redis::exists($hashkey)){
            $jsonstr = \Redis::get($hashkey);
            $data = isset($jsonstr) ? json_decode($jsonstr, true) : array();
        }else {
            $barcode_arr = explode(' ', $barcode);
            if (!empty($barcode_arr)) {
                $this->ql->post('http://jyj.eccang.com/default/index/login',[
                    'userName' => 'PHP03',
                    'userPass' => 'PHP123456'
                ])->get('http://jyj.eccang.com/transfer/packing/list?quick=141');
                foreach ($barcode_arr as $item) {
//                    form表单
//                    http://jyj.eccang.com/purchase/purchase-request-orders/list/page/1/pageSize/20
//                    userMark:
//                    E3:
//                    po_staus:
//                    pay_status:
//                    E2:
//                    E5:
//                    audit_id:
//                    re_examine_user_id:
//                    E1:
//                    po_code:
//                    sku_type: 2
//                    productBarcode: PALLET
//                    dateFor:
//                    dateTo:

                    $post_data = [
                        'userMark' => '',
                        'E3' => '',
                        'po_staus' => '',
                        'pay_status' => '',
                        'E2' => 1,
                        'E5' => '',
                        'audit_id' => '',
                        're_examine_user_id' => '',
                        'E1' => '',
                        'po_code' => '',
                        'sku_type' => '2',
                        'productBarcode' => $barcode,
                        'dateFor' => '',
                        'dateTo' => ''
                    ];

                    $this->ql->post('http://jyj.eccang.com/purchase/purchase-request-orders/list/page/1/pageSize/1000', $post_data);
                    $content =  $this->ql->getHtml();
                    $result = json_decode($content, true);
                    if(!empty($result['data'])) {
                        foreach ($result['data'] as $item) {
                            array_push($data, $item);
                        }
                    }
                }
            }

            \Redis::setex($hashkey, 60, json_encode($data));
        }
        return $data;
    }

    /**
     * 查询子产品SKU的库存
     * @param $barcode
     */
    public function querySkus($barcode){
        $data = array();
        $hashkey = md5('querySkus'.'-'.$barcode);
        if(\Redis::exists($hashkey)){
            $jsonstr = \Redis::get($hashkey);
            $data = isset($jsonstr) ? json_decode($jsonstr, true) : array();
        }else {
            $barcode_arr = explode(' ', $barcode);
            if (!empty($barcode_arr)) {
                $jar = new CookieJar();
                $this->ql->post('http://jyj.eccang.com/default/index/login', [
                    'userName' => 'PHP03',
                    'userPass' => 'PHP123456'
                ], ['cookies' => $jar]);
                $cookieArr = $jar->toArray();
                $sessionid = $cookieArr[1]['Value'];
                $this->ql->get('http://jyj-eb.eccang.com/?session_id='.$sessionid.'&a=a');
                foreach ($barcode_arr as $item) {
//                    Form表单
//                    http://jyj-eb.eccang.com/product/product-combine-relation/list/page/1/pageSize/20
//                    platform:
//                    product_sku_type: 1
//                    product_sku: J040154-Small
//                    sub_sku_query_type: 1
//                    pcr_product_sku:
//                    user_account:
//                    warehouse_id:
//                    user_id:
//                    user_id_type:
//                    country_code:
//                    pcr_percent_from:
//                    pcr_percent_to:
//                    pcr_quantity_from:
//                    pcr_quantity_to:
//                    create_date_from:
//                    create_date_to:
//                    sort: desc
//                    update_date_from:
//                    update_date_to:
//                    update_sort: desc
//                    is_more: 0
//                    mapping_type: 3
                    //获取目的地列表
                    $post_data = [
                        'platform' => '',
                        'product_sku_type' => 1,
                        'product_sku' => $barcode,
                        'sub_sku_query_type' => 1,
                        'pcr_product_sku' => '',
                        'user_account' => '',
                        'warehouse_id' => '',
                        'user_id' => '',
                        'user_id_type' => '',
                        'country_code' => '',
                        'pcr_percent_from' => '',
                        'pcr_percent_to' => '',
                        'pcr_quantity_from' => '',
                        'pcr_quantity_to' => '',
                        'create_date_from' => '',
                        'create_date_to' => '',
                        'sort' => 'desc',
                        'update_date_from' => '',
                        'update_date_to' => '',
                        'update_sort' => 'desc',
                        'is_more' => 0,
                        'mapping_type' => 3

                    ];
                    $this->ql->post('http://jyj-eb.eccang.com/product/product-combine-relation/list/page/1/pageSize/20', $post_data);
                    $content = $this->ql->getHtml();
                    $result = json_decode($content, true);
                    if(!empty($result['data'])) {
                        $skus = array();
                        foreach ($result['data'] as $item) {
                            // $nitem = array();
                            // $nitem['product_sku'] = isset($item['product_sku']) ? $item['product_sku'] : '';
                            // $nitem['pcr_product_sku'] = isset($item['pcr_product_sku']) ? $item['pcr_product_sku'] : '';
                            // $nitem['pcr_product_name_cn'] = isset($item['pcr_product_name_cn']) ? $item['pcr_product_name_cn'] : '';
                            // $nitem['pcr_quantity'] = isset($item['pcr_quantity']) ? $item['pcr_quantity'] : 0;
                            // $data[] = $nitem;
                            if(!empty($item['product_sku'])) $skus[] = $item['product_sku'];
                        }
                        if(!empty($skus)){                            
                            $skustr = implode(' ', $skus);
                            $data = $this->querySubStore($skustr);
                        }
                    }
                }
            }

            \Redis::setex($hashkey, 5, json_encode($data));
        }

        return $data;
    }

    /**
     * 组合的子产品仓库查询
     * @param $barcode
     * @return mixed
     */
    public function querySubStore($barcode){
        $data = array();
        $hashkey = md5('querySubStore'.'-'.$barcode);
        if(\Redis::exists($hashkey)){
            $jsonstr = \Redis::get($hashkey);
            $data = isset($jsonstr) ? json_decode($jsonstr, true) : array();
        }else {
            $barcode_arr = explode(' ', $barcode);
            if (!empty($barcode_arr)) {
                $this->ql->post('http://jyj.eccang.com/default/index/login', [
                    'userName' => 'PHP03',
                    'userPass' => 'PHP123456'
                ])->get('http://jyj.eccang.com/warehouse/Inventory/new-list/page/1/pageSize/20');
                foreach ($barcode_arr as $item) {
                    //                Form表单
                    //                http://jyj.eccang.com/warehouse/Inventory/new-list/page/1/pageSize/20
                    //                sale_status:
                    //                product_receive_status:
                    //                product_status: 1
                    //                category[]:
                    //                operationType: E1_like
                    //                product_barcode: J040626-WG-WHITE_TABLE
                    //                product_title_type: like_product_title
                    //                like_product_title:
                    //                supplier_id:
                    //                supplier_name:
                    //                order_by:
                    //                is_recommend_lc_code:
                    //                lcType: 1
                    //                recommend_lc_code_like:
                    //                prl_id:
                    //                person_type: 1
                    //                person:
                    //                date_type: 1
                    //                dateFor:
                    //                dateTo
                    //获取目的地列表
                    $post_data = [
                        'sale_status' => '',
                        'product_receive_status' => '',
                        'product_status' => 1,
                        'category' => [],
                        'operationType' => 'E1', //E1、E1_like
                        'product_barcode' => $item,
                        'product_title_type' => 'like_product_title',
                        'supplier_id' => '',
                        'supplier_name' => '',
                        'order_by' => '',
                        'is_recommend_lc_code' => '',
                        'lcType' => 1,
                        'recommend_lc_code_like' => '',
                        'prl_id' => '',
                        'person_type' => 1,
                        'person' => '',
                        'date_type' => 1,
                        'dateFor' => '',
                        'dateTo' => '',

                    ];
                    $this->ql->post('http://jyj.eccang.com/warehouse/Inventory/new-list/page/1/pageSize/1000', $post_data);
                    $content = $this->ql->getHtml();
                    $result = json_decode($content, true);
//                    dd($content);
                    if(!empty($result['data'])) {
                       foreach ($result['data'] as $item) {
                           $nitem = array();
                           if(!empty($item['warehouseDetail'])){
                               array_pop($item['warehouseDetail']);
                                foreach ($item['warehouseDetail'] as $oitem){
                                    $nitem['product_barcode'] = $item['product_barcode']; //产品代码
                                    $nitem['product_title'] = $item['product_title']; //产品名称
                                    $nitem['warehouse'] = $oitem['warehouse']; //仓库
                                    $nitem['pi_purchase_onway'] = strval($oitem['pi_purchase_onway']); //采购在途
                                    $nitem['pi_in_used'] = strval($oitem['pi_in_used']); //可用、可售
                                    $nitem['pi_warning_qty'] = strval($oitem['pi_warning_qty']); //预警
                                    $nitem['pi_can_sale_days'] = strval($oitem['pi_can_sale_days']); //可售天数
                                    $nitem['pi_no_stock'] = strval($oitem['pi_no_stock']); //缺货
                                    $nitem['pi_no_stock_days'] = strval($oitem['pi_no_stock_days']); //缺货天数
                                    $nitem['expected_date'] = 0; //预计到货日期
                                    //获取采购在途数据
                                    $pdata = [
                                        'wid' => $oitem['warehouse_id'],
                                        'pid' => $oitem['product_id'],
                                        'status' => 5
                                    ];
                                    $this->ql->post('http://jyj.eccang.com/warehouse/inventory/get-purchase-on-way-detail/', $pdata);
                                    $ltcontent = $this->ql->getHtml();
                                    $ltrs = json_decode($ltcontent, true);
                                    if(!empty($ltrs)){
                                        $num = 0;
                                        foreach ($ltrs as $ors){
                                            $num += $ors['rd_receiving_qty'];
                                            if($num >= $oitem['pi_no_stock']){
                                                $nitem['expected_date'] = $ors['expected_date'];
                                                break;
                                            }
                                        }
                                    }
                                    array_push($data, $nitem);
                                }
                           }
                       }
                    }
                }
            }

            \Redis::setex($hashkey, 5, json_encode($data));
        }

        return $data;
    }
}
